﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebApiV.Data;

namespace WebApiV.Domain
{
    public class EfRespository<T> : IRespository<T> where T : BaseEntity
    {
        private readonly Admin10086Db db;

        private DbSet<T> entity;

        public DbSet<T> Entity
        {
            get
            {
                if (entity == null)
                {
                    entity = db.Set<T>();
                }
                return entity;
            }
        }

        public IQueryable<T> Table
        {
            get
            {
                return entity;
            }
        }

        public EfRespository(Admin10086Db admin)
        {
            db = admin;
        }


        public void Delete(int id)
        {
            var del = Table.Where(x => x.Id == id).FirstOrDefault();
            Delete(del);
        }

        public void Delete(T entity)
        {
            Entity.Remove(entity);
            db.SaveChanges();
        }

        public void Insert(T entity)
        {
            Entity.Add(entity);
            db.SaveChanges();
        }

        public void InsertBlck(IEnumerable<T> list)
        {
            Entity.AddRange(list);
            db.SaveChanges();
        }
        public T GetById(int id)
        {
            return entity.Where(x => x.Id == id).FirstOrDefault();
        }

        public void Update(T entity)
        {
            Entity.Update(entity);
            db.SaveChanges();
        }

        public void Delete(IEnumerable<T> entities)
        {
            Entity.RemoveRange(entities);
            db.SaveChanges();
        }
    }
}
